﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DONGACS.DTO;
using QLPKWeb.BussinessDelegate.Base;
using QLPKWeb.BussinessDelegate.CommonDelegate;
using QLPKWeb.BussinessDelegate.PhanQuyen;
using QLPKWeb.Controllers.Base;
using QLPKWeb.Models.FormBean.PhanQuyen;
using Webdiyer.WebControls.Mvc;
using DONGACS.Common;
using DONGACS.Domain;

namespace QLPKWeb.Controllers
{
    public class DepartmentsController : AbstractController<DepartmentsForm, DepartmentsDto, Int32, Departments>
    {
        DepartmentsServiceDelegate DepartmentsServiceDelegate = new DepartmentsServiceDelegate();
        CommonDelegate CommonDelegate = new CommonDelegate();

       //this.BaseServiceDelegate = new BaseServiceDelegate<DepartmentsDto, Departments>();
        
        //Cách này sử dụng cơ chế IOC để khởi tạo đối tựong
        //public DepartmentsServiceDelegate DepartmentsServiceDelegate
        //{
        //    get
        //    {
        //        return (DepartmentsServiceDelegate)this.BaseServiceDelegate;
        //    }
        //}



        UsersServiceDelegate UsersServiceDelegate = new UsersServiceDelegate();
        //
        // GET: /Departments/

        public ActionResult List(int? id)// id : page number
        {
            
            DepartmentsForm form = new DepartmentsForm();

            BuildDepartmentsList(form);

            form.DepartmentsPagedList = new PagedList<DepartmentsDto>(form.DepartmentsDtoList, id ?? 1, CommonVariables.PaggedItemsPerPage);

            form.PageNumber = id ?? 1;
            form.ID = -1;
            form.CreateDate = DateTime.Now;
            form.UpdateDate = DateTime.Now;


            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }
            
            return View("Index", form);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create(int? id)// id : page number
        {
            return Redirect("~/Departments/List/" + id);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Create(DepartmentsForm form)
        {
            //Lấy thông tin Job Title mới từ Form
            DepartmentsDto newDepartments = this.DepartmentsServiceDelegate.BuildNewDepartments(form);

            //Lưu Job Titele mới xuống database
            int idReturn = -1;
            bool isCreateJobTitle = this.DepartmentsServiceDelegate.AddNewDepartments(newDepartments, ref idReturn);

            form.ID = idReturn;
            //Thông báo kết quả tạo Job Title
            form.MessageCreateDepartments = isCreateJobTitle ? "Tạo Phòng ban thành công !" : "Tạo Phòng ban lỗi, xin thử lại !";

            //Refesh form
            BuildDepartmentsList(form);
            form.ID = idReturn;
            form.CreateDate = DateTime.Now;
            form.UpdateDate = DateTime.Now;

            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }

            //Phân trang
            //int id = 1;
            form.DepartmentsPagedList = new PagedList<DepartmentsDto>(form.DepartmentsDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);


            return View("Index", form);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int? id)// id : page number
        {
            return Redirect("~/Departments/List/" + id);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(DepartmentsForm form, int? id)
        {
            form.ID = form.DepartmentID;

            //Lấy thông tin Job Title mới từ Form
            DepartmentsDto newDepartment = this.DepartmentsServiceDelegate.BuildEditDepartments(form);

            //Lưu Job Titele mới xuống database

            bool isUpdateJobTitle = this.DepartmentsServiceDelegate.Update(newDepartment);

            //Thông báo kết quả tạo Job Title
            form.MessageEditDepartments = isUpdateJobTitle ? "Cập nhật Phòng ban thành công !" : "Cập nhật Phòng ban lỗi, xin thử lại !";

            //Refesh form
            BuildDepartmentsList(form);

            form.CreateDate = newDepartment.CreateDate;
            form.UpdateDate = newDepartment.UpdateDate;

            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }
            //Phân trang
            //int id = 1;
            form.DepartmentsPagedList = new PagedList<DepartmentsDto>(form.DepartmentsDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);

            return View("Index", form);
        }

        public ActionResult Delete(string departmentID)
        {
            this.DepartmentsServiceDelegate.Delete(departmentID);
            return RedirectToAction("List");
        }

        public JsonResult DepartmentsEditAjax(int id)
        {
            DepartmentsDto dto = this.DepartmentsServiceDelegate.GetDepartmentsById(id.ToString());
            
            var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.CreateBy));
            var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.UpdateBy)); 

            dto.CreateByUser = dto.CreateBy != 0 && userCreate != null ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
            dto.UpdateByUser = dto.UpdateBy != 0 && userUpdate != null ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;
            dto.CreateDateString = dto.CreateDate.ToString("dd/MM/yyyy");
            dto.UpdateDateString = dto.UpdateDate.ToString("dd/MM/yyyy");

            dto.Chief = CommonDelegate.GetDisplayNameByUserId(dto.IdChief.ToString());


            return Json(dto, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DepartmentsNewAjax()
        {
            var userLogin = UsersServiceDelegate.GetUsersById(Session["USERID"].ToString());
            var newObj = new object[2] { userLogin != null ? userLogin.LastName + " " + userLogin.FirstName : string.Empty, DateTime.Now };

            return this.Json(newObj, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsExistDepartmentAjax(string departmentName)
        {
            DepartmentsDto dto = this.DepartmentsServiceDelegate.GetDepartmentsByName(departmentName);

            bool result = dto != null ? true : false;

            return this.Json(result, JsonRequestBehavior.AllowGet);
        }

        private void BuildDepartmentsList(DepartmentsForm form)
        {
            //Lấy danh sách user không bị đánh dấu IsDelete = 1
            form.IdChiefList = UsersServiceDelegate.GetAllUsersActive();

            //Lấy danh sách Department không bị đánh dấu IsDelete = 1
            form.DepartmentsDtoList = DepartmentsServiceDelegate.GetAllEntities();
            //form.DepartmentsDtoList = BaseServiceDelegate.GetAllEntities();
            foreach (var departmentsDto in form.DepartmentsDtoList)
            {   //lấy tên ngừoi tạo hay thay đổi thông tin department
                var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(departmentsDto.UpdateBy));
                var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(departmentsDto.CreateBy));
               // departmentsDto.UpdateByUser = departmentsDto.UpdateBy != 0 ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;
               // departmentsDto.CreateByUser = departmentsDto.CreateBy != 0 ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
            }
        }

    }
}
